package com.xiaomaoguai.socket.one;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketAddress;

/**
 * @Description :
 * @FileName: MyServer.java
 * @Author :WeiHui.Zhang
 * @Data : 2015年6月18日 下午5:16:51
 * @Version:V1.00
 */
public class MyServer {

	private static boolean flag;

	public static void main(String[] args) {
		ServerSocket serverSocket = null;
		try {
			serverSocket = new ServerSocket(9999);

			Socket socket = serverSocket.accept();

			SocketAddress socketAddress = socket.getRemoteSocketAddress();
			System.out.println(socketAddress.toString());

			if(socketAddress.toString().contains("10.0.2.45")){
				flag = true;
			}

			BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));

			PrintWriter writer = new PrintWriter(socket.getOutputStream());

			while (true) {
				if (flag) {
					writer.println("nice to meet you!");
				}
				String msg = reader.readLine();
				System.out.println(msg);
				writer.println("Server Recevied : " + msg);
				writer.flush();
				if (msg.equals("bye")) {
					break;
				}
			}

			socket.close();

		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (serverSocket != null) {
				try {
					serverSocket.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}

	}
}
